#![allow(clippy::too_many_arguments)]

use ormlite::Model;

use crate::entity::{Page, PaginationOptions};
use crate::vo::sys_user_vo::SysUserPageReqVo;
use crate::SQLX;

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Model)]
pub struct SysUser {
    #[ormlite(primary_key)]
    pub user_id: Option<i64>,
    pub user_name: Option<String>,
    pub password: Option<String>,
    pub name: Option<String>,
    pub phone: Option<String>,
    pub admin: Option<i64>,
    pub remark: Option<String>,
    pub state: Option<i32>,
    pub create_time: Option<String>,
    pub org_id: Option<i64>,
}

impl SysUser {
    pub async fn query_user(
        user_name: Option<String>,
        org_id: Option<i64>,
    ) -> anyhow::Result<Option<SysUser>> {
        let db = SQLX.get().ok_or(anyhow::anyhow!("db error"))?;
        let user = sqlx::query_as::<_, SysUser>(
            "select * from sys_user where user_name = ? and org_id = ?",
        )
            .bind(user_name)
            .bind(org_id)
            .fetch_optional(db)
            .await?;
        Ok(user)
    }
    pub async fn query_page(
        org_id: i64,
        payload: SysUserPageReqVo,
    ) -> anyhow::Result<Page<SysUser>> {
        let paginate_option = PaginationOptions {
            page_no: payload.page_no,
            page_size: payload.page_size,
        };
        let mut sql = format!(r#"select * from sys_user where org_id ={}"#, org_id);
        if payload.user_name.is_some() {
            sql.push_str(&format!(
                " and user_name like '%{}%'",
                payload.user_name.unwrap()
            ));
        }
        let pages = super::fetch_page::<SysUser>(&sql, &paginate_option).await?;
        Ok(pages)
    }
}
